package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import seracher.DocSearcher;
import seracher.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/searcher")
public class SearcherServlet extends HttpServlet {

    private  DocSearcher docSearcher=new DocSearcher();
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.首先先拿到参数
        //2.根据参数然后调用相应的函数
        //跨域问题
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        resp.setHeader("Access-Control-Max-Age", "3600");
        String query=req.getParameter("query");
        if(query==null || query.length()==0) {
            resp.sendError(404,"你输入的参数非法，请检查参数");
            return ;
        }
        //设置返回数据的类型
        System.out.println("参数是："+query);
        resp.setContentType("application/json;charset=utf-8");
        List<Result> results = docSearcher.search(query);
        objectMapper.writeValue(resp.getWriter(),results);
    }
}
